/**
 * Created by Administrator on 2018/10/18.
 */



// 格式化责任人
function dutyFormatter(value, row, index) {
    console.log(value);
    if (value === '1') {
        return '<a class="btn-set" href="javascript:void(0);">未设置</a >';
    } else if (value === '0') {
        return '<span></span>';
    } else {
        return '<a class="btn-set" href="javascript:void(0);">' + value + '</a>';
    }
}

// 格式化时间
function dateFormatter(value, row, index) {
    return value ? value : '';
}


// 检测对象类型
function type(obj) {
    return Object.prototype.toString.call(obj).replace(/\[object (\w+)\]/, '$1').toLowerCase();
}

// 格式化操作
function operateFormatter(value, row, index) {
    if (row.pid == 0) {
        return '<a class="btn btn-xs btn-default btn-set btn-up" href="javascript:void(0);">上移</a><a class="btn btn-xs btn-default btn-set btn-down" href="javascript:void(0);">下移</a>';
    } else {
        return '';
    }
}


function getTemplateId(src) {
    // console.log(src);
    var qs = src.split('?')[1];
    var args = {};
    var items = qs.length ? qs.split('&') : [];
    var len = items.length;
    if (qs.length == 0) {
        // alert("没有查询字符串,退出！");
        return;
    }
    for (var i = 0; i < len; i++) {
        var item = items[i].split("=");
        args[decodeURIComponent(item[0])] = decodeURIComponent(item[1]);
    }
    return args['templateId'];
}

//上移 arr, 待移元素index-1，待移元素index
//下移 arr, 待移元素index，待移元素index+1
function swapArray(arr, index1, index2) {
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr;
}

function removeArrayItem(arr, val) {
    var index = arr.indexOf(val);
    if (index > -1) {
        arr.splice(index, 1);
    }
}


/*var gongzuoxiang  = [
    {name:'zopp',order:3},
    {name:'gpp',order:1},
    {name:'yjj',order:2},
    {name:'yjsj',order:1},
    {name:'yjaj',order:3}
];

function compare(property){
    return function(a,b){
        var value1 = a[property];
        var value2 = b[property];
        return value1 - value2;
    }
}
console.log(gongzuoxiang.sort(compare('order')));*/

$(function () {
    // 进入模板页加载loading
    var layerIndex = layer.load(1);

    //var baseURL = "/";  // 请求前缀
    var pWindow = window.parent;
    var sSrc = $('#main-content iframe', pWindow.document).attr('src');
    var token = window.localStorage.getItem("token");
    var templateId = getTemplateId(sSrc);    // 模板id
    var tableData = [];

    var phaseList = [];
    var templateList = [];
    $.get(baseURL + 'generator/basetaskinfo/queryTask/' + templateId, {token: token}, function (data) {
        console.log(data);
        var result = data.list;
        phaseList = data.phaseList; // 阶段列表
        templateList = data.templateList;   // 模板列表
        console.log(result);
        // result[0] renwu
        // result[1] gongzuoxiang
        /*[123,]
        var renwu = [];
        for (var i = 0; i < renwu.length; i++) {
            var id = parseInt(result[i].id);
            var pid = parseInt(result[i].pid);
            result[i].id = id;
            result[i].pid = pid;
            tableData.push(result[i]);
        }
        var gongzuoxiang = [];
        var sortGongzuoxiang = gongzuoxiang.sort(compare('order'));
        for (var i = 0; i < sortGongzuoxiang.length; i++) {
            var id = parseInt(sortGongzuoxiang[i].id);
            var pid = parseInt(sortGongzuoxiang[i].pid);
            sortGongzuoxiang[i].id = id;
            sortGongzuoxiang[i].pid = pid;
            tableData.push(sortGongzuoxiang[i]);
        }*/

        for (var i = 0; i < result.length; i++) {
            for (var k = 0; k < result[i].length; k++) {
                // _this.tableData.push(result[i][k]);
                var id = parseInt(result[i][k].id);
                var pid = parseInt(result[i][k].pid);
                result[i][k].id = id;
                result[i][k].pid = pid;
                tableData.push(result[i][k]);
            }
        }



        console.log(tableData);
        var oTable = $('#stage-table');
        oTable.bootstrapTable({
            data: tableData,
            striped: false,
            checkboxHeader: true,
            idField: 'id',
            clickToSelect: true,
            columns: [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'name',
                    title: '任务名称'
                },

                {
                    field: 'phaseName',
                    title: '阶段类型',
                    align: 'center'
                },
                {
                    field: 'deliveryGoods',
                    align: 'center',
                    title: '文档描述'
                },
                {
                    field: 'operation',
                    title: '操作',
                    align: 'center',
                    events: 'operateEvents',
                    formatter: 'operateFormatter'
                }
            ],

            treeShowField: 'name',
            parentIdField: 'pid',
            onResetView: function (data) {
                oTable.treegrid({
                    initialState: 'collapsed',// 所有节点都折叠
                    treeColumn: 1,
                    expanderExpandedClass: 'glyphicon glyphicon-minus',  //图标样式
                    expanderCollapsedClass: 'glyphicon glyphicon-plus',
                    onChange: function () {
                        oTable.bootstrapTable('resetWidth');
                    }
                });
                //只展开树形的第一级节点
                oTable.treegrid('getRootNodes').treegrid('expand');
            }
        });
        window.taskId = [];
        if (tableData.length > 0) {
            for (var i = 0; i < tableData.length; i++) {
                if (tableData[i].pid == 0) {
                    var index = tableData[i].twOrder - 1;
                    taskId[index] = tableData[i].id;
                }
            }
        }
        // 关闭页面加载时的loading
        layer.close(layerIndex);

    });

    window.operateEvents = {
        //行上下移
        "click .btn-set": function (e, value, row, index) {
            console.log(tableData);

            // console.log($(this));
            // console.log($(this).hasClass('btn-up'));
            // console.log($(this).hasClass('btn-down'));

            if ($(this).hasClass('btn-up')) {
                if (taskId.indexOf(row.id) == 0) {
                    alert("这是第一个")
                } else {
                    var current = taskId.indexOf(row.id);
                    swapArray(taskId, current - 1, current);
                }
            } else if ($(this).hasClass('btn-down')) {
                if (taskId.indexOf(row.id) == taskId.length - 1) {
                    alert("这是最后一个")
                } else {
                    var current = taskId.indexOf(row.id);
                    swapArray(taskId, current, current + 1);
                }
            }

            var newTableData = [];
            for (var i = 0; i < tableData.length; i++) {
                if (tableData[i].pid == 0) {
                    var newIndex = taskId.indexOf(tableData[i].id);
                    tableData[i].twOrder = newIndex + 1;
                    newTableData[newIndex] = tableData[i];
                } else {
                    newTableData.push(tableData[i]);
                }
            }
            var oTable = $('#stage-table');
            $(oTable).bootstrapTable("load", newTableData);
        }
    };

    $('#operate-pane').on('click', '.btn-operate', function () {
        var aSelections = $('#stage-table').bootstrapTable('getSelections');
        console.log(aSelections);

        if ($(this).hasClass('btn-add-task')) {
            // 添加任务

            $.get(baseURL + 'generator/basetaskinfo/queryTemplateTask/' + templateId, {token: token}, function (data) {
                var addTableData = [];
                var taskHTML = '<div class="container-fluid">' +
                    '            <table id="addTask-table"></table>' +
                    '           </div>' +
                    '            <div class="layer-btn-pane">' +
                    '                <button id="tableTaskEnd" class="btn btn-primary" type="button">保存</button>' +
                    '            </div>' +
                    '        </div>';
                layer.open({
                    type: 1,
                    skin: 'layui-layer-demo', //样式类名
                    closeBtn: 1, //不显示关闭按钮
                    anim: 2,
                    area: ['75%', '60%'],
                    shadeClose: true, //开启遮罩关闭
                    content: taskHTML
                });


                console.log(data);
                var result = data.list;
                console.log(result);
                for (var i = 0; i < result.length; i++) {
                    for (var k = 0; k < result[i].length; k++) {
                        var id = parseInt(result[i][k].id);
                        var pid = parseInt(result[i][k].pid);
                        result[i][k].id = id;
                        result[i][k].pid = pid;
                        addTableData.push(result[i][k]);
                    }
                }
                var oTable = $('#addTask-table');

                console.log(oTable);
                oTable.bootstrapTable({
                    data: addTableData,
                    striped: false,
                    checkboxHeader: true,
                    idField: 'id',
                    clickToSelect: true,
                    expandAllRows: true,
                    columns: [
                        {
                            field: 'ck',
                            checkbox: true
                        },
                        {
                            field: 'name',
                            title: '任务名称'
                        },

                        {
                            field: 'phaseName',
                            title: '阶段类型',
                            align: 'center'
                        }
                    ],

                    treeShowField: 'name',
                    parentIdField: 'pid',
                    onResetView: function (data) {
                        oTable.treegrid({
                            initialState: 'collapsed',// 所有节点都折叠
                            treeColumn: 1,
                            expanderExpandedClass: 'glyphicon glyphicon-minus',  //图标样式
                            expanderCollapsedClass: 'glyphicon glyphicon-plus',
                            onChange: function () {
                                oTable.bootstrapTable('resetWidth');
                            }
                        });
                        //只展开树形的第一级节点
                        oTable.treegrid('getRootNodes').treegrid('expand');
                    }
                });

                //添加任务
                $('.layui-layer-content').on('click', '#tableTaskEnd', function () {
                    var getSelectRows = oTable.bootstrapTable('getSelections');
                    console.log(getSelectRows);
                    var tabaData = [];
                    if (getSelectRows != null || getSelectRows.length != 0) {
                        for (var i = 0; i < getSelectRows.length; i++) {
                            var temp = {};
                            temp.id = getSelectRows[i].id;
                            temp.templateId = templateId;
                            tabaData.push(temp);
                        }
                        $.ajax({
                            type: "POST",
                            headers: {
                                token: token
                            },
                            url: baseURL + "generator/basetaskinfo/templateAddTask",
                            contentType: "application/json",
                            data: JSON.stringify(tabaData),
                            success: function (r) {
                                if (r.code == 0) {
                                    alert('操作成功', function (index) {
                                        var pWindow = window.parent;
                                        var oIframe = $('#main-content iframe', pWindow.document);
                                        oIframe.attr('src', 'modules/base/templates.html?templateId=' + templateId);
                                    });
                                } else {
                                    alert(r.msg);
                                }
                            }
                        });
                    } else {
                        alert('请选择需要添加的任务');
                    }

                });
            });


        } else if ($(this).hasClass('btn-add-work')) {
            // 添加工作项
            console.log(aSelections);
            if (aSelections.length > 1) {
                alert('只能选一个任务');
                return false;
            } else if (aSelections.length == 0) {
                alert('请选择一个任务');
                return false;
            } else if (aSelections[0].pid != '0') {
                alert('你选择的不是任务');
                return false;
            } else {
                var workitemHTML = '<div class="layer-content">' +
                    '<div class="layer-inp-pane">' +
                    '            <div class="layer-inp-cell">' +
                    '                <label for="">工作项名称：<input id="addWorkitemName" class="form-control" type="text" style="width: 200px;" placeholder="工作项名称"></label>' +
                    '            </div>' +
                    '            <div class="layer-inp-cell">' +
                    '                <label for="">工作项完成天数：<input type="text" class="form-control" style="width: 200px;" placeholder="工作项完成天数"></label>' +
                    '            </div>' +
                    '            <div class="layer-inp-cell">' +
                    '                <label for="">交付物描述：<input id="addDeliveryGoods" class="form-control" type="text" style="width: 200px;" placeholder="交付物描述"></label>' +
                    '            </div>' +
                    '</div>' +
                    '            <div class="layer-btn-pane">' +
                    '                <button id="workitemEnd" class="btn btn-primary" type="button">保存</button>' +
                    '            </div>' +
                    '        </div>';
                layer.open({
                    type: 1,
                    skin: 'layui-layer-demo', //样式类名
                    closeBtn: 1, //不显示关闭按钮
                    anim: 2,
                    area: ['500px', 'auto'],
                    shadeClose: true, //开启遮罩关闭
                    content: workitemHTML
                });

                $('.layer-content').on('click', '#workitemEnd', function () {
                    var addWorkitemName = $('#addWorkitemName').val();
                    var addDeliveryGoods = $('#addDeliveryGoods').val();
                    if (addWorkitemName == '') {
                        alert('工作项名称不能为空');
                        return false;
                    }
                    if (addDeliveryGoods == '') {
                        addDeliveryGoods = '无';
                    }
                    $.get(baseURL + 'generator/baseworkiteminfo/add/' + addWorkitemName + '/' + addDeliveryGoods + '/' + aSelections[0].id, {token: token}, function (r) {
                        console.log(r);
                        if (r.code == 0) {
                            layer.close(layer.index);
                            alert('操作成功', function (index) {
                                console.log(index);
                                var pWindow = window.parent;
                                var oIframe = $('#main-content iframe', pWindow.document);
                                oIframe.attr('src', 'modules/base/templates.html?templateId=' + templateId);

                            });
                        } else {
                            alert(r.msg);
                        }
                    });
                })
            }
        } else if ($(this).hasClass('btn-taskPreservation')) {
            // 保存
            var postData = [];
            for (var i = 0; i < taskId.length; i++) {
                var temp = {};
                temp.id = taskId[i];
                temp.twOrder = i + 1;
                temp.templateId = templateId;
                postData.push(temp);
            }
            console.log(postData);
            $.ajax({
                type: "POST",
                url: baseURL + "generator/basetaskinfo/updateOrder",
                contentType: "application/json",
                data: JSON.stringify(postData),
                success: function (r) {
                    if (r.code == 0) {
                        alert('操作成功', function (index) {
                            $("#jqGrid").trigger("reloadGrid");
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });

        } else if ($(this).hasClass('btn-add-down')) {
            // 下移
            console.log(aSelections);
        } else if ($(this).hasClass('btn-add-del')) {
            // 删除
            // console.log(aSelections);
            window.taskList = [];
            if (tableData.length > 0) {
                for (var i = 0; i < tableData.length; i++) {
                    if (tableData[i].pid == 0) {
                        var index = tableData[i].twOrder - 1;
                        taskList[index] = tableData[i].id;
                    }
                }
            }
            console.log(taskList);
            removeArrayItem(taskList, aSelections[0].id);
            var newTable = [];
            for (var i = 0; i < tableData.length; i++) {
                if (tableData[i].pid == 0) {
                    var newIndex = taskList.indexOf(tableData[i].id);
                    tableData[i].twOrder = newIndex + 1;
                    newTable[newIndex] = tableData[i];
                } else {
                    newTable.push(tableData[i]);
                }
            }
            console.log(taskList);
            console.log(newTable);

            var postDatas = [];
            for (var i = 0; i < taskList.length; i++) {
                var temp = {};
                temp.id = taskList[i];
                temp.twOrder = i + 1;
                temp.templateId = templateId;
                postDatas.push(temp);
            }
             console.log(postDatas);



            if (aSelections.length > 1) {
                alert('只能选一个目标');
                return false;
            } else if (aSelections.length == 0) {
                alert('请选一个目标');
                return false;
            }
            var parameter = '';
            var url = '';
            if (aSelections[0].pid != '0') {
                /!*选择的是工作项*!/
                url = 'generator/baseworkiteminfo/deleteWorkitem';
                parameter = '/' + aSelections[0].id;
            } else if (aSelections[0].pid == '0') {
                url = 'generator/basetaskinfo/deleteTask';
                parameter = '/' + aSelections[0].id + '/' + templateId;
            }

            layer.confirm('确定删除当前选中项吗？', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                // console.log(baseURL + url + parameter);
                if (aSelections[0].pid != '0') {
                    $.get(baseURL + url + parameter, {token: token}, function (r) {
                        console.log(r);
                        if (r.code == 0) {
                            layer.close(layer.index);
                            alert('操作成功', function (index) {
                                console.log(index);
                                var pWindow = window.parent;
                                var oIframe = $('#main-content iframe', pWindow.document);
                                oIframe.attr('src', 'modules/base/templates.html?templateId=' + templateId);

                            });
                        } else {
                            alert(r.msg);
                        }
                    });
                }else if (aSelections[0].pid == '0') {
                    $.ajax({
                        type: "POST",
                        url: baseURL +  url + parameter,
                        contentType: "application/json",
                        data: JSON.stringify(postDatas),
                        success: function (r) {
                            if (r.code == 0) {
                                alert('操作成功', function (index) {
                                    console.log(index);
                                    var pWindow = window.parent;
                                    var oIframe = $('#main-content iframe', pWindow.document);
                                    oIframe.attr('src', 'modules/base/templates.html?templateId=' + templateId);
                                });
                            } else {
                                alert(r.msg);
                            }
                        }
                    });
                }

                // layer.msg('的确很重要', {icon: 1});
            }, function () {
                // layer.msg('也可以这样', {
                //     time: 20000, //20s后自动关闭
                //     btn: ['明白了', '知道了']
                // });
                console.log('不删了');
            });
        } else if ($(this).hasClass('btn-back')) {
            // 保存
            // console.log(aSelections);
            var pWindow = window.parent;
            var oIframe = $('#main-content iframe', pWindow.document);
            // console.log(oIframe);
            oIframe.attr('src', 'modules/base/basetemplate.html');
        }
    });
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        projectEntity: {},
        areaList: [],
        tableData: []
    },
    methods: {
        getTemplateId: function (src) {
            console.log(src);
            var qs = src.split('?')[1];
            var args = {};
            var items = qs.length ? qs.split('&') : [];
            var len = items.length;
            if (qs.length == 0) {
                // alert("没有查询字符串,退出！");
                return;
            }
            for (var i = 0; i < len; i++) {
                var item = items[i].split("=");
                args[decodeURIComponent(item[0])] = decodeURIComponent(item[1]);
            }
            return args['templateId'];
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.projectEntity = {};
        },
        update: function (event) {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo(id)
        },
        del: function (event) {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + "generator/projectentity/delete",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function (id) {
            $.get(baseURL + "generator/projectentity/info/" + id, function (r) {
                vm.projectEntity = r.projectEntity;
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                page: page
            }).trigger("reloadGrid");
        }

    }
});